<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/2
 * Time: 下午2:57
 * 积分操作类
 */

namespace app\common\controller;


use app\api\controller\Pub;
use app\common\model\CardBonusRule;
use app\common\model\CardCzgive;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Bonus extends Wxoption
{
    //积分变动充值时调用（无充送规则）
    /*
     * $user 会员卡号code   会员卡card_id    会员卡ID id
     * $arr giveid 充值规则ID(默认传递空)  增加积分add_balance
     *
     * */
    public function cz_bonus_rec($user,$arr)
    {
        try {
            $CardMember = new CardMember();
            $CardUserGet = new CardUserGet();
            //更新积分
            $card = $CardMember->where('card_id', $user['card_id'])->field('supply_bonus,bonus_rule')->find();
            //判断是否开启积分
            if ($card['supply_bonus'] == 1) {
                $bonus_rule = json_decode($card['bonus_rule'], true);
                //比例和积分
                $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                $add_bonus = floor($arr['add_balance'] * $bili);
                //同步微信数据
                $bonus['code'] = $user['code'];
                $bonus['card_id'] = $user['card_id'];
                $bonus['record_bonus'] = '充值赠送';
                $bonus['bonus'] = $add_bonus;
                $resu['bonus'] = $this->updatabonus($bonus);
                //判断更新
                if ($resu['bonus']['errcode'] == 0) {
                    $CardUserGet->where('id', $user['id'])->setField('bonus', $resu['bonus']['result_bonus']);
                    $bonusdata = $resu;
                    $bonusdata['code'] = 0;
                    $bonusdata['message'] = $resu;
                    $bonusdata['add_bonus'] = $add_bonus;
                    //写入积分记录
//                    $this->cz_rec_user($user,$arr,$bonus);
                } else {
                    $bonusdata = ['code' => 9005, 'message' => $resu,'add_bonus'=>$add_bonus];

                }

            }else{
                $bonusdata = ['code' => 9004, 'message' => '无积分','add_bonus'=>''];
            }
        } catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage()];
        }
        return $bonusdata;
    }



    //积分变动 冲送用
    /*
     * $user 会员卡号code   会员卡card_id    会员卡ID id
     * $arr giveid 充值规则ID(默认传递空)  增加积分add_balance
     *
     * */
    public function cs_bonus_rec($user)
    {
        try {
            $CardMember = new CardMember();
            $card = $CardMember->where('card_id', $user['card_id'])->find();
            if ($card['supply_bonus'] == 1) {
                $CardCzgive = new CardCzgive();
                $CardUserGet = new CardUserGet();
                $zs_bonus = $CardCzgive->where('id', $user['giveid'])->value('bonus');
                if ($zs_bonus > 0) {
                    //同步微信数据
                    $bonusb['code'] = $user['code'];
                    $bonusb['card_id'] = $user['card_id'];
                    $bonusb['record_bonus'] = '充值赠送';
                    $bonusb['bonus'] = $zs_bonus;
                    $resut = $this->updatabonus($bonusb);
                    if ($resut['errcode'] == 0) {
                        //更新积分
                        $CardUserGet->where('id', $user['id'])->setField('bonus', $resut['result_bonus']);
                        $bonusdata = ['code' => 0, 'message' => '赠送成功！','add_bonus'=>$zs_bonus];

                        //写入积分记录
                        $bonusb['source'] = $user['source'];
//                        $this->cs_rec_user($user,$bonusb);
                    } else {
                        $bonusdata = ['code' => 9001, 'message' => '赠送失败！','add_bonus'=>$zs_bonus];
                    }
                } else {
                    $bonusdata = ['code' => 9002, 'message' => '无赠送积分！','add_bonus'=>''];

                }
            }else{
                $bonusdata = ['code' => 9004, 'message' =>'无积分','add_bonus'=>''];
            }
        } catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage(),'add_bonus'=>''];
        }
        return $bonusdata;
    }




     //积分充值方法--手动
    /*
     * id:会员卡系统内部ID
     * record_bonus:核销备注
     * bonus：变动积分
     * hx_fs:核销方式
     * type:类型
     * cate:变动类型
     * reason：变动原因
     * source：变动来源
     * mid：商户系统内部编号
     * username:操作人
     *
     * */
    public function bonus_rec($param)
    {
        try {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['id' => $param['id']])->field('code,card_id,openid')->find();
            $option['card_id'] = $user['card_id'];
            $option['code'] = $user['code'];
            $option['orderid'] = $param['orderid'];
            $option['num'] =   $param['bonus'];
            $option['bd_cate'] = 'bonus';
            $option['type'] = 1;//变动 1增加 2减少
            $option['cate'] = 4;  //变动类型
            $option['pay_cate'] = $param['hx_fs']; //支付方式
            $option['source'] = $param['source'];  //来源
            $option['remark'] = '消费赠送'; //备注
            $option['action_user'] = $param['username'];//操作人
            $Fztest = new WnCardObj($option);
            $record_id = $Fztest->init();
            $ActionLogs=new ActionLogs();
            $ActionLogs->writelog("osapi","clientlogs","bonus_rec","2:",$option);
            //END
//            $CardUserUpdate = new CardUserUpdate();
//            $datas['code'] = $user['code'];
//            $datas['card_id'] = $user['card_id'];
//            $datas['openid'] = $user['openid'];
//            $datas['record_bonus'] = $param['record_bonus'];
//            $datas['hx_fs'] = $param['hx_fs'];            //方式
//            $datas['type'] = $param['type'];             //类型
//            $datas['cate'] = $param['cate'];             //类别
//            $datas['reason'] = $param['reason'];           //原因
//            $datas['source'] = $param['source'];           //来源
//            $datas['mid'] = $param['mid'];
//            $datas['add_bonus'] = $param['bonus'];
//            $datas['con_username'] = $param['username'];
//            $datas['create_time'] = time();
//            $CardUserUpdate->allowField(true)->save($datas);
//            $record_id = $CardUserUpdate->id;
            $rarr = ['code' => '0', 'message' => '增加成功！', 'record_id' => $record_id];
        } catch (\Exception $e) {
            $rarr = ['code' => 9999, 'message' => $e->getMessage()];
            file_put_contents('/data2/html/osapi/bonus_rec.txt', 'e:' . json_encode($rarr) . PHP_EOL, FILE_APPEND);
        }
        return $rarr;
    }
    

    //积分核销方法
    public function bonus_con($param){
        try {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['id' => $param['id']])->find();
            $bonus['code'] = $user['code'];
            $bonus['card_id'] = $user['card_id'];
            $bonus['record_bonus'] = $param['record_bonus'];
            $bonus['bonus'] = -$param['bonus'];
            $resu = $this->updatabonus($bonus);
            if ($resu['errcode'] == 0) {
                $map['card_id'] = $user['card_id'];
                $map['code'] = $user['code'];
                $res = $CardUserGet->where($map)->setField('bonus', $resu['result_bonus']);
                if ($res) {
                    $CardUserUpdate = new CardUserUpdate();
                    $datas['code'] = $user['code'];
                    $datas['card_id'] = $user['card_id'];
                    $datas['openid'] = $user['openid'];
                    $datas['record_bonus'] = $param['record_bonus'];
                    $datas['hx_fs'] = $param['hx_fs'];            //方式
                    $datas['type'] = $param['type'];             //类型
                    $datas['cate'] = $param['cate'];             //类别
                    $datas['reason'] = $param['reason'];           //原因
                    $datas['source'] = $param['source'];           //来源
                    $datas['mid'] = $param['mid'];
                    $datas['del_bonus'] = $param['bonus'];
                    $datas['con_username'] = $param['username'];
                    $datas['create_time'] = time();
                    $CardUserUpdate->allowField(true)->save($datas);
                    $record_id = $CardUserUpdate->id;
                    //carduserlog 记录
                    $datas['up_id'] = $record_id;
//                    $this->rec_user_bonus($datas);
                    $rarr = ['code' => '0', 'message' => '核销成功！','record_id'=>$record_id];
                } else {
                    $rarr = ['code' => '9001', 'message' => '更新失败！'];
                }
            } else {
                $rarr = ['code' => '9003', 'message' => '核销失败！'];
            }
        } catch (\Exception $e) {
            $rarr = ['code' => 9099, 'message' => $e->getMessage()];
        }
        return $rarr;
    }

    //消费后积分变动
    /*
     *
     * $openid
     * $arr   price   merchantid username
     *
     */
    public function pay_bonus($openid,$arr){
        try {
            $Pub = new Pub();
            $user = $Pub->get_card_userinfo($arr['merchantid'],$openid);

            $CardMember = new CardMember();
            //更新积分
            $card = $CardMember->where('card_id', $user['card_id'])->field('supply_bonus,bonus_rule')->find();
            //判断是否开启积分
            if ($card['supply_bonus'] == 1) {
                $bonus_rule = json_decode($card['bonus_rule'], true);
                //比例和积分
                $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                $add_bonus = floor($arr['price'] * $bili);
                //END
                //禁止规则
                $CardBonusRule = new CardBonusRule();
                $mar['end_time'] = ['egt', time()];
                $mar['card_id'] = $user['card_id'];
                $mar['type'] = 1;
                $mar['statu'] = 0;
                $ruledis = $CardBonusRule->where($mar)->find();
                if (empty($ruledis)) {
                    //多倍规则
                    $mab['end_time'] = ['egt', time()];
                    $mab['card_id'] = $user['card_id'];
                    $mab['type'] = 2;
                    $mab['statu'] = 0;
                    $rulemax = $CardBonusRule->where($mab)->find();
                    //多倍积分
                    if ($rulemax) {
                        $bonus = $add_bonus * $rulemax['bonus_max'];               //积分变动
                        //普通积分
                    } else {
                        $bonus = $add_bonus;
                    }
                    $Paylog = new Paylog();
                    $payinfo = $Paylog->where('orderid',$arr['orderid'])->field('source,pay_fs')->find();           //来源
                    $datas['orderid'] = $arr['orderid'];
                    $datas['bonus'] = $bonus;
                    $datas['id'] = $user['id'];
                    $datas['card_id'] = $user['card_id'];
                    $datas['record_bonus'] = '消费赠送';
                    $datas['hx_fs'] = $payinfo['pay_fs'];            //方式
                    $datas['type'] = 6;             //类型
                    $datas['cate'] = 1;             //类别
                    $datas['reason'] = 1;           //原因
                    $datas['source'] = $payinfo['source'];           //来源
                    $datas['mid'] = $arr['merchantid'];
                    $datas['username'] = $arr['username'];
                    $this->bonus_rec($datas);
//                    $this->rec_user_bonus($datas);
                    $bonusdata = ['code' => 0, 'message' => '无积分', 'add_bonus' => ''];
                } else {
                    $bonusdata = ['code' => 9004, 'message' => '无积分', 'add_bonus' => ''];
                }
            } else {
                $bonusdata = ['code' => 9004, 'message' => '无积分', 'add_bonus' => ''];
            }
        }catch (\Exception $e){
            $bonusdata = ['code' => "FAIL", 'message' => '系统错误'.$e->getMessage()];
        }
        return $bonusdata;


    }



    //积分更新微信操作
    public function updatabonus($arr)
    {
        try {
            //实例化微信
            $options = $this->options($arr['card_id'],'card_id');

            $WxObj = new Wxobjopen($options);
            $data = [
                'code' => $arr['code'],
                'card_id' => $arr['card_id'],
                'record_bonus' => $arr['record_bonus'],       //说明
                'add_bonus' => $arr['bonus'],             //积分变动值  负数为减少
                'notify_optional' => [
                    'is_notify_bonus' => true,
                    'is_notify_balance' => false,
                    'is_notify_custom_field1' => false,
                ],
            ];
            $res = $WxObj->updateUserInfo($data);
            if ($res['errcode'] == 0){
                $Level = new Level();
                $Level->checklevel($arr['card_id'],$arr['code'],$res['result_bonus']);
            }

        } catch (\Exception $e) {
            $res = ['errcode' => 9099, 'message' => $e->getMessage()];
        }
        return $res;
    }

    //记录表
    /*
     * mid up_id openid con_username card_id code add_boonus/del_bonus  record_bonus  orderid type cate reason source
     *
     *
     */
    public function rec_cardlogs($arr)
    {
        try {
            $CardUserLog = new CardUserLog();
            $data['mid'] = $arr['mid'];
            $data['up_id'] = $arr['up_id'];
            $data['openid'] = $arr['openid'];
            $data['con_username'] = $arr['con_username'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            if (isset($arr['add_bonus'])) {
                $data['num'] = $arr['add_bonus'];
            }
            if (isset($arr['del_bonus'])) {
                $data['num'] = -$arr['del_bonus'];
            }
            if (isset($arr['record_bonus'])){
                $data['record'] = $arr['record_bonus'];           //记录
            }
            if (isset($arr['orderid'])) {
                $data['orderid'] = $arr['orderid'];
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);
        }catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
        }
    }

    //giveid   price card_id
    public function getrechargebonus($giveid,$price,$card_id){
        if ($giveid == ''){
            $bonus = $this->getbonuscate($price,$card_id);
        }else{
            $CardCzgive = new CardCzgive();
            $bonus = $CardCzgive->where('id', $giveid)->value('bonus');
        }
        return $bonus;
    }

    public function getbonuscate($num,$card_id)
    {

        $CardMember = new CardMember();
        $map['card_id'] = $card_id;
        $cardinfo = $CardMember->where($map)->field('bonus_rule,supply_bonus')->find();
        //是否开启积分
        if ($cardinfo['supply_bonus'] == 1) {
            $bonus_rule = json_decode($cardinfo['bonus_rule'], true);
            //比例和积分
            $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
            $add_bonus = floor($num * $bili);
        } else {
            $add_bonus = 0;
        }

        $rule = $this->bonusgives($card_id);
        $bonus = $rule * $add_bonus;
        return $bonus;
    }

    public function bonusgives($card_id)
    {

        $CardBonusRule = new CardBonusRule();
        //禁止规则
        $map['end_time'] = ['egt', time()];
        $map['card_id'] = $card_id;
        $map['statu'] = 0;
        $rule = $CardBonusRule->where($map)->find();
        if ($rule) {
            if ($rule['type'] == 1) {
                $bili = 0;
            } else {
                $bili = $rule['bonus_max'];
            }
        } else {
            //普通
            $bili = 1;
        }
        return $bili;
    }

}